package com.meizhuang.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.meizhuang.base.BaseController;
import com.meizhuang.entity.*;
import com.meizhuang.result.JsonResult;
import com.meizhuang.service.CouponService;
import com.meizhuang.service.UserCouponService;
import com.meizhuang.service.UserIntegralRecordService;
import com.meizhuang.service.UserIntegralService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "coupon")
public class CouponController extends BaseController {

    @Autowired
    private CouponService couponService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private UserIntegralRecordService userIntegralRecordService;
    /**
     * 优惠劵列表
     * @return
     */
    @RequestMapping("/list")
    public JsonResult list(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new LinkedHashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        Date now =new Date();

        EntityWrapper<Coupon>  couponEntityWrapper= new EntityWrapper<>();
        couponEntityWrapper.le("start_time",now);
        couponEntityWrapper.ge("end_time",now);

        retMap.put("coupons",couponService.selectList(couponEntityWrapper).stream().filter(f->f.getQuota() > f.getTakeCount()).collect(Collectors.toList()));

        //查询已领取的
        EntityWrapper<UserCoupon>  userCouponEntityWrapper= new EntityWrapper<>();
        userCouponEntityWrapper.eq("uid",userSession);
        List<UserCoupon> userCoupons = userCouponService.selectList(userCouponEntityWrapper);
        retMap.put("userCoupons",userCoupons);
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 领取
     * @return
     */
    @RequestMapping("/receive")
    public JsonResult receive(HttpServletRequest request, HttpServletResponse response){

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        Map<String,Object> retMap = new LinkedHashMap<>();

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<Coupon>  couponEntityWrapper= new EntityWrapper<>();
        String counponId = request.getParameter("counpon_id");

        if(counponId == null){
            retMap.put("msg", "优惠劵ID不能为空");
            return JsonResult.buildError(retMap);
        }

        couponEntityWrapper.eq("id",counponId);
        Coupon configConpon = couponService.selectOne(couponEntityWrapper);

        if( null ==  configConpon){
            retMap.put("msg", "无效的优惠劵");
            return JsonResult.buildError(retMap);
        }

        Date now =new Date();

        Lock lock = new ReentrantLock();
        try {
            lock.lock();

            EntityWrapper<UserCoupon> wrapper = new EntityWrapper<>();
            wrapper.eq("coupon_id",counponId);
            wrapper.eq("uid",userSession);
//            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            wrapper.where("coupon_id={0} and uid ={1} and to_days(create_time) = to_days({2}) ",counponId,userSession,simpleDateFormat.format(now));
//            wrapper.last("limit 1");
            UserCoupon userCoupon = userCouponService.selectOne(wrapper);

            if(null != userCoupon ){
                retMap.put("msg", "该优惠劵已领取");
                return JsonResult.buildError(retMap);
            }


            if(now.before( configConpon.getStartTime())  ||  now.after(configConpon.getEndTime()) ){
                retMap.put("msg", "领取时间无效");
                return JsonResult.buildError(retMap);
            }

            if(configConpon.getTakeCount().intValue() >= configConpon.getQuota().intValue()){
                retMap.put("msg", "优惠劵已发完");
                return JsonResult.buildError(retMap);
            }

            userCoupon = new UserCoupon();
            userCoupon.setUid(userSession);
            userCoupon.setCouponId(Integer.parseInt(counponId));
            userCoupon.setName(configConpon.getName());
            userCoupon.setDesc(configConpon.getDesc());
            userCoupon.setStatus(1);
            userCoupon.setType(configConpon.getType());
            userCoupon.setUsed(configConpon.getUsed());
            userCoupon.setWithAmount(configConpon.getWithAmount());
            userCoupon.setUsedAmount(configConpon.getUsedAmount());
            userCoupon.setCreateTime(now);
            userCouponService.insert(userCoupon);

            configConpon.setTakeCount(configConpon.getTakeCount()+1);
            couponService.updateById(configConpon);
        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }
        return JsonResult.buildSuccess(retMap);
    }

    @RequestMapping("/add")
    public JsonResult add(Coupon counpon){

        Map<String,Object> retMap = new LinkedHashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        if(StringUtils.isBlank(counpon.getName())){
            retMap.put("msg", "优惠券名称为空");
            return JsonResult.buildError(retMap);
        }

        Lock lock = new ReentrantLock();

        try {
            lock.lock();

            EntityWrapper<Coupon>  couponEntityWrapper= new EntityWrapper<>();
            couponEntityWrapper.eq("name",counpon.getName());
            Coupon coupon = couponService.selectOne(couponEntityWrapper);


            if(null != coupon ){
                retMap.put("msg", "优惠劵名称已存在");
                return JsonResult.buildError(retMap);
            }

            switch (counpon.getUsed()) {
                case 10:
                case 20:
                    break;
                default:{
                    retMap.put("msg", "used 可用于：10店铺优惠券  20商品优惠券");
                    return JsonResult.buildError(retMap);
                }
            }

            Date now =new Date();

            if(now.before( counpon.getStartTime())  ||  now.after(counpon.getEndTime()) ){
                retMap.put("msg", "发放时间无效");
                return JsonResult.buildError(retMap);
            }

            if(now.after(counpon.getValidEndTime()) ){
                retMap.put("msg", "使用时间无效");
                return JsonResult.buildError(retMap);
            }

            counpon.setCreateTime(now);

            couponService.insert(counpon);

            EntityWrapper<UserIntegral> userIntegralEntityWrapper = new EntityWrapper<UserIntegral>();
            userIntegralEntityWrapper.eq("uid", userSession);
            UserIntegral userIntegral = userIntegralService.selectOne(userIntegralEntityWrapper);

            if(null == userIntegral ){
                userIntegral = new UserIntegral();
                userIntegral.setUid(userSession);
                userIntegral.setQuota(10);
                userIntegral.setCreateTime(new Date());
                userIntegral.setUpdateTime(userIntegral.getCreateTime());
                userIntegralService.insert(userIntegral);
            }else{
                userIntegral.setQuota(userIntegral.getQuota()+10);
                userIntegral.setUpdateTime(new Date());
                userIntegralService.updateById(userIntegral);
            }

            UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
            userIntegralRecord.setUid(userSession);
            userIntegralRecord.setQuota(10);
            userIntegralRecord.setCreateTime(new Date());
            userIntegralRecord.setUpdateTime(userIntegralRecord.getCreateTime());
            userIntegralRecord.setSource("优惠劵");
            userIntegralRecordService.insert(userIntegralRecord);

        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }
        return JsonResult.buildSuccess(retMap);
    }


    @RequestMapping("/update")
    public JsonResult update(Coupon counpon){

        Map<String,Object> retMap = new LinkedHashMap<>();

        if(null == counpon.getId()){
            retMap.put("msg", "优惠券ID为空");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<Coupon>  couponEntityWrapper= new EntityWrapper<>();
        couponEntityWrapper.eq("id",counpon.getId());
        Coupon originCoupon = couponService.selectOne(couponEntityWrapper);

        if(null == originCoupon ){
            retMap.put("msg", "优惠劵不存在");
            return JsonResult.buildError(retMap);
        }

        Date now =new Date();

        if(now.before( counpon.getStartTime())  ||  now.after(counpon.getEndTime()) ){
            retMap.put("msg", "发放时间无效");
            return JsonResult.buildError(retMap);
        }

        if(now.before( counpon.getValidStartTime())  ||  now.after(counpon.getValidEndTime()) ){
            retMap.put("msg", "使用时间无效");
            return JsonResult.buildError(retMap);
        }

        couponService.updateById(counpon);

        return JsonResult.buildSuccess(retMap);
    }


    @RequestMapping("/delete")
    public JsonResult delete(Coupon counpon){

        Map<String,Object> retMap = new LinkedHashMap<>();

        if(null == counpon.getId()){
            retMap.put("msg", "优惠券ID为空");
            return JsonResult.buildError(retMap);
        }


        couponService.deleteById(counpon.getId());

        return JsonResult.buildSuccess(retMap);
    }
}
